package alpha.com.google.code.mechanic.janitor.ui;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.beans.PojoProperties;
import org.eclipse.core.databinding.observable.map.IObservableMap;
import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.jface.databinding.viewers.ObservableMapLabelProvider;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

import alpha.com.google.code.mechanic.janitor.controller.ContextData;
import alpha.com.google.code.mechanic.janitor.controller.MechanicTaskSource;
import alpha.com.google.code.mechanic.janitor.model.ContextsCollector;
import alpha.com.google.code.mechanic.janitor.model.DefaultSysFilePath;
import alpha.com.google.code.mechanic.janitor.model.IContext;
import alpha.com.google.code.mechanic.janitor.model.ProjectContext;

import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;

/**
 * The dialog is to manage users defined Contexts. Within the dialog, users can
 * add/delete Contexts and switch between Contexts.
 * 
 * Last_edited: Dec 17, 2014
 * 
 * @History
 * 1. Add a new button "Rename" for renaming a Context.
 * @author jingjiejiang
 * @edited Nov 11, 2014
 * 1) Add class DefaultValidator;
 * 2) Add a private method: void renameDirectory(String newCtxName);
 * 3) Add a new button "Rename".
 * 
 * 2. 
 * @author jingjiejiang
 * @since Nov 29, 2014
 * 1) Changes the constructor public ContextsMgtDialog(Shell parentShell,
 * boolean resDefPrefs), delete two parameters(before it has 4 parameters).
 * a. Add a new field: ContextData ctxData;
 * b. Add two new methods: void checkSelContext() and
 * boolean initContextData().
 * 
 * 2) Changes the behaviors when delete a Context: pop up a confirmation dialog.
 * 
 * 3. 
 * @author jingjiejiang
 * @since Dec 17, 2015
 * 1) change the method createCtxDir(), only allow to pop up information dialog
 * if all the new added Contexts has been successfully created. 
 * 
 * @author jingjiejiang
 * @since Apr 11, 2014
 */
public class ContextsMgtDialog extends Dialog {

  //The title of the dialog.
  private static final String CONTEXT_DIALOG_TITLE = "Context Management";
  //SELCONTEXT is for the selected context; and UNSELCONTEXT is to indicate those unselected ones.
  private static final Image SELCONTEXT = MechanicPlugin.getImageDescriptor("icons/ticking_icon.png").createImage();
  private static final Image UNSELCONTEXT = MechanicPlugin.getImageDescriptor("icons/non_ticking_icon.png").createImage();
 
  // private DataBindingContext m_bindingContext;
  private Composite tableContainer;
  private Label lbl_ProjList;
  private Table contextTable;
  private TableViewer contextTableViewer; 
  private TableViewerColumn tbleContextNameClmn; 
  private TableViewerColumn tblContextLocClmn; 
  private Composite compoBtns; 
  private Button btnClearSelect;
  private Button btnDeleteContext;
  private Button btnDeteleAll;
  private Button btnAddButton;
  private Button btnResDefPreferences;
  private Button btnRename;
  
  // The value represents whether restore all defaults preferences before
  // switching Contexts.
  private boolean resDefPrefs;

  // the current selected context
  private IContext selContext;
  // the previous selected context
  private IContext preSelContext;
  
  // for saving the data of a new added project context
  private ProjectContext newProjContext = new ProjectContext();
  // data for storing the user defined contexts.
  private ContextsCollector ctxsCollector;
  // the original contexts (without the new added ones)
  private ContextsCollector preCtxsCollector = new ContextsCollector();
  // The file that is to store the contexts data.
  private File ctxFile;
  // The list that is to store the new added Context directories.
  private List<String> contextsDir;
  
  private ContextData ctxData;
  
  private MechanicTaskSource taskSrc = new MechanicTaskSource();
  
  /**
   * Create the dialog.
   *
   * @param parentShell 
   * @param resDefPrefs The value represents whether restore all defaults
   * preferences before switching Contexts.(NB: The function is not valid at the moment)
   *
   */
  public ContextsMgtDialog(Shell parentShell, boolean resDefPrefs) {
    super(parentShell);
    
    setShellStyle(SWT.TITLE);
    
    if(initContextData()) {
      
      checkSelContext();
      ctxsCollector = ctxData.getContextsCollector();
      preCtxsCollector.copyAllContexts(ctxsCollector.getContextList());
      preSelContext = ctxData.getContextsCollector().getSelContext();
      // Initialize selContext as the same value of preSelContext, in may happen at the end
      // no changes at the Contexts list window are made.
      selContext = ctxData.getContextsCollector().getSelContext(); 
      this.ctxFile = ctxData.getContextsFile();
      setResDefPrefs(resDefPrefs);
      
      contextsDir = new ArrayList<String>();  
    } 
     
  }
  
  private boolean initContextData() {
    
    ctxData = new ContextData();
    try {
      ctxData.readContextsFile();
    } catch (Exception e) {
      
      MessageDialog.openError(getParentShell(), "Couldn't read the Contexts"
          + " information from context.con file.", e.getMessage());
      return false;
    }
    
    return true;
  }
  
  private void checkSelContext() {
    
    // Check whether the selected Context is still in the task source list,
    // if not, deselect the Context.
    MechanicTaskSource sources = new MechanicTaskSource();
    sources.checkSelCtxExist(ctxData);
  }
  
  /**
   * Name the ContextSwitchDialog.
   */
  @Override
  protected void configureShell(Shell shell) {
      super.configureShell(shell);
      if (CONTEXT_DIALOG_TITLE != null) {
    shell.setText(CONTEXT_DIALOG_TITLE);
    }
  }
  
//  @Override
//  protected void setShellStyle(int arg0){
//    super.setShellStyle(getShellStyle() & ~SWT.CLOSE & ~SWT.MIN);
//  }
//  
  public boolean isResDefPrefs() {
    return resDefPrefs;
  }

  public void setResDefPrefs(boolean resDefPrefs) {
    this.resDefPrefs = resDefPrefs;
  }
  
  /**
   * When delete Contexts, invoke the methods to change the value of selContext
   *.
   */
  private void initializeSelContext() {
    
    Iterator<IContext> iterator = ctxsCollector.getContextList().iterator();
    if (iterator.hasNext()) {
      selContext = iterator.next();
      selContext.setSelected(true);
    }
    // if there exists no Context, set selContext as null
    else {
      selContext = null;
    }
    
  }

  /**
   * Create contents of the dialog.
   * @param parent
   */
  @Override
  protected Control createDialogArea(Composite parent) {
    tableContainer = (Composite) super.createDialogArea(parent);
    
    createProjListLbl(tableContainer);
    createContextTable(tableContainer);
    createContextsNameClmn(contextTableViewer);
    createContextLocClmn(contextTableViewer);

    createButtonsComposite(tableContainer);
    createAddBtn();
    createRenameBtn();
    createDelContextBtn();
    createDelAllBtn();
    createClearSelBtn();
    
    //Label label = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
    Label label = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
    GridData gd_label = new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1);
    gd_label.widthHint = 200;
    label.setLayoutData(gd_label);
    
    initContextListTblBinding();
   
    return tableContainer;
  }
  
  private void createResDefPrefsBtn () {
    
    btnResDefPreferences = new Button(tableContainer, SWT.CHECK);
    btnResDefPreferences.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        setResDefPrefs(true);
      }
    });
    btnResDefPreferences.setText("Always restore default preferences before"
        + " switching Contexts");
    btnResDefPreferences.setSelection(resDefPrefs);
  }
  
  /**
   * Delete the directory of the current Context from the hard drive.
   *
   * @param context
   */
  private void delCurCtxDir (IContext context) {
    
    String dir = context.getFileLocation();
    
    File index = new File(dir);
    if (!index.exists()) {
      return;
    }
    else {
      String[] entries = index.list();
      for(String s: entries){
          File currentFile = new File(index.getPath(),s);
          currentFile.delete();
      }
           
      index.delete();
    }
  }
  
  private void delAllCtxDir () {
    
    Set<IContext> ctxs = ctxsCollector.getContextList();
    Iterator<IContext> iterator = ctxs.iterator();
    
    while (iterator.hasNext()) {
      delCurCtxDir (iterator.next());
    }
  }
  
  private void createClearSelBtn () {
    
    btnClearSelect = new Button(compoBtns, SWT.NONE);
    btnClearSelect.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
       
        ctxsCollector.clearContextSelection();
        selContext = null;
        contextTableViewer.refresh();
        initContextListTblBinding();
      }
    });
    
    btnClearSelect.setBounds(359, 0, 101, 28);
    btnClearSelect.setText("Clear Select");

  }
  
  private void createRenameBtn() {
    
    btnRename = new Button(compoBtns, SWT.NONE);
    btnRename.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        
        if (selContext != null) {
          InputDialog dialog = new InputDialog(getParentShell(),
              "", "Please input a new Context name:", selContext.getName(), new DefaultValidator());
          int dialogopen = dialog.open();
          if (Dialog.OK == dialogopen) {
            
            String newname = dialog.getValue();
            
            selContext.setName(newname);
            renameDirectory(newname);
            initContextListTblBinding();
            selContext = null;
            
            dialog.close();
          } else if (Dialog.CANCEL == dialogopen) {
            dialog.close();
          }
        } else {
          MessageDialog.openInformation(getParentShell(), "Warning", "Please "
              + "select the Context that you need to rename first!");
        }
      }
    });
    btnRename.setBounds(89, 0, 94, 28);
    btnRename.setText("Rename");
  }
  
  private void renameDirectory(String newCtxName) {
    
    File oldpath = new File(selContext.getFileLocation());
    DefaultSysFilePath defaultpath = new DefaultSysFilePath();
    defaultpath.initCtxFileDir();
    String newloc = defaultpath.getDefaultSysFilePath() + newCtxName;
    
    File newpath = new File(newloc);
    selContext.setFileLocation(newloc);
    if ( oldpath.isDirectory() ) {
      oldpath.renameTo(newpath);
      try {
        ctxsCollector.serializeContextsInfo(ctxFile);
      } catch (IOException e) {
        MessageDialog.openError(getParentShell(), "Couldn't save the changes"
            + " of the new Context name.", e.getMessage());
      }
    } 
    
  }
  
  class DefaultValidator implements IInputValidator {

    public String isValid(String newText) {
      return null;
    }
    
  }
  
  private void createDelAllBtn () {
    
    btnDeteleAll = new Button(compoBtns, SWT.NONE);
    
    btnDeteleAll.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        
        delAllCtxDir();
        ctxsCollector.resetContextList();
        contextTableViewer.refresh();
        selContext = null;
        initContextListTblBinding();
      }
    });

    btnDeteleAll.setBounds(267, 0, 94, 28);
    btnDeteleAll.setText("Delete All");
  }
  
  private void createDelContextBtn () {
    
    btnDeleteContext = new Button(compoBtns, SWT.NONE);
    
    btnDeleteContext.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        
        if (MessageDialog.openConfirm(getParentShell(), "", "Are you sure "
            + "you want to delete the selected Context?")){
          
          delCurCtxDir(ctxsCollector.getSelContext());
          // delete the selected context.
          ctxsCollector.delSelContext();
          try {
            ctxData.saveContextsInfo();
          } catch (IOException error) {
            MessageDialog.openError(getParentShell(), "Couldn't save the "
                + "changes to context.con file.", error.getMessage());
            return;
          }
          contextTableViewer.refresh();

         // selContextName = "";
          initializeSelContext();
          initContextListTblBinding();
        }
        
      }
    });
    
    btnDeleteContext.setBounds(178, 0, 94, 28);
    btnDeleteContext.setText("Delete");
    
  }
  
  private void createAddBtn () {
    
    this.btnAddButton = new Button(compoBtns, SWT.NONE);
    
    btnAddButton.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        Shell parentShell = Display.getCurrent().getActiveShell();
        CreateContextDialog contextDialog = new CreateContextDialog(parentShell); 
        if (contextDialog.open() == CreateContextDialog.OK) {
          
          newProjContext = contextDialog.getProjContext();
          if (newProjContext != null) {
            
            if (!hasSameName(newProjContext.getName())) {

              contextsDir.add(newProjContext.getFileLocation());
              ctxsCollector.addContext(newProjContext);
              initContextListTblBinding();

            }
            else {
              
              MessageDialog.openWarning(parentShell,  " ",
                  "There already exist a Context with the same name. Please change"
                  + " the name for the new Context.");
            }
          }
        }
      }
    });
    
    btnAddButton.setBounds(0, 0, 94, 28);
    btnAddButton.setText("Add");
  }
  
  /**
   * Check whether the new added context has a name clash with the existing contexts  
   *
   * @param name
   * @return
   */
  private boolean hasSameName (String contextname) {
    
    boolean hasSame = false;
    
    Iterator<IContext> iterator = ctxsCollector.getContextList().iterator();
    
    while (iterator.hasNext()) {
      
      IContext tempcontext = iterator.next();
      if (contextname.equals(tempcontext.getName())) {
        
        hasSame = true;
      }
    }
    
    return hasSame;
  }
  
  private void createButtonsComposite(Composite container) {
    
    // The code that create the check box has to be here.
    // Otherwise, the position of the box will be under the "Add" button.
    createResDefPrefsBtn();
    
    compoBtns = new Composite(container, SWT.NONE);
    GridData gd_composite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_composite.widthHint = 463;
    gd_composite.heightHint = 30;
    compoBtns.setLayoutData(gd_composite);
    
  }
  
  private void createProjListLbl(Composite composite) {

    lbl_ProjList = new Label(composite, SWT.NONE);
    lbl_ProjList.setText("Contexts list:");
    
  }
  
  private void createContextTable (Composite composite) {
    
    contextTableViewer = new TableViewer(tableContainer, SWT.BORDER | SWT.FULL_SELECTION);
    contextTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
      public void selectionChanged(SelectionChangedEvent event) {
        
        IStructuredSelection selection = (IStructuredSelection)event.getSelection();
        // Object fstElement = selection.getFirstElement();
        Iterator<?> iterator = selection.iterator();
        
        if (iterator.hasNext()) {
          
          IContext context = (IContext) iterator.next();
          String path = context.getFileLocation();
          File file = new File(path);
          // This is to prevent selecting an non-created context.
          if (file.exists()){
            ctxsCollector.clearContextSelection();
            
            selContext = context;
            selContext.setSelected(true);
          }
          else {
            //Shell pshell = Display.getCurrent().getActiveShell();
            MessageDialog.openWarning(getShell(), "Warning", "You are selecting"
            + " a Context that has not created in the hard drive.");
            
            // This is to get the focus back.
            Point dialogpoint = getInitialLocation(getInitialSize());
            Robot robot = null;
            try {
              robot = new Robot();
            } catch (AWTException e) {
              MessageDialog.openError(getParentShell(), "Low-level input"
                  + " control not allowed!", e.getMessage());
            }
            
            //g2d.setColor(Color.blue);

            if (robot != null) {
              robot.mouseMove(dialogpoint.x + 200, dialogpoint.y + 40);
              robot.mousePress(InputEvent.BUTTON1_MASK);
              robot.mouseRelease(InputEvent.BUTTON1_MASK);
            }
            
          }
        }
        
        // refresh the context list table.
        contextTableViewer.refresh();
        initContextListTblBinding();
      }
    });
    contextTable = contextTableViewer.getTable();
    contextTable.setLinesVisible(true);
    contextTable.setHeaderVisible(true);
    contextTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
  }

  private void createContextsNameClmn (TableViewer tableviewer) {
    
    tbleContextNameClmn = new TableViewerColumn(tableviewer, SWT.NONE);
    TableColumn tblclmnContextName = tbleContextNameClmn.getColumn();
    tblclmnContextName.setWidth(200);
    tblclmnContextName.setText("Name");
    
  }
  
  private void createContextLocClmn (TableViewer tableviewer) {
    
    tblContextLocClmn = new TableViewerColumn(contextTableViewer, SWT.FILL);
    TableColumn tblclmnFileLoc = tblContextLocClmn.getColumn();
    tblclmnFileLoc.setWidth(500);
    tblclmnFileLoc.setText("Files Location");  
    
  }
  
  /**
   * Create contents of the button bar.
   * @param parent
   */
  @Override
  protected void createButtonsForButtonBar(Composite parent) {
    createButton(parent, IDialogConstants.CANCEL_ID,
        IDialogConstants.CANCEL_LABEL, false);
    createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
        true);    
  }

  /**
   * Return the initial size of the dialog.
   */
  @Override
  protected Point getInitialSize() {
    return new Point(484, 400);
  }
    
  private void initContextListTblBinding() {
    
    ObservableSetContentProvider setContentProvider = new ObservableSetContentProvider();
    IObservableMap[] observeMaps = PojoObservables.observeMaps(setContentProvider.getKnownElements(), IContext.class, new String[]{"name", "fileLocation"});
    contextTableViewer.setLabelProvider(new ContextObservableMapLabelProvider(observeMaps));
    contextTableViewer.setContentProvider(setContentProvider);
    IObservableSet contextListCtxsCollectorObserveSet = PojoProperties.set("contextList").observe(ctxsCollector);
    contextTableViewer.setInput(contextListCtxsCollectorObserveSet);
  }
  
  private class ContextObservableMapLabelProvider extends ObservableMapLabelProvider {

    public ContextObservableMapLabelProvider(IObservableMap[] observeMaps) {
      super(observeMaps);
    }
    
    @Override 
    public Image getColumnImage(Object element, int columnIndex) {
      
      IContext context = (IContext) element;
      Image image = null;
      
      switch (columnIndex) {
      case 0:
        image = isRowSelected(context);
        break;
      case 1:
        break;
      default:
          break;        
      }
      
      return image;
    }
  }
  
  private Image isRowSelected (IContext context) {
    
    Image image = UNSELCONTEXT;
    
    if (context.isSelected()) {
      image = SELCONTEXT;
    }
    
    return image;
  }
  
  public IContext getSelContext() {
    
    return selContext;
  }
  
  /**
   * If a user create new Contexts, then create directories that related
   * to the Contexts.
   * @return
   */
  private void createCtxDir () {
    
    int newctx = contextsDir.size();
    
    // only execute the method when there exists at least one Context
    //if (this.contextsDir != null && ctxsCollector.getSelContext() != null) {
    if (0 != newctx) {
      // TODO JL we now know that one or more contexts will be created
      Iterator<String> iterator = contextsDir.iterator();
      while (iterator.hasNext()) {
        
        String dir = iterator.next();
        boolean success = new File(dir).mkdirs();
        if (!success) {
          // Directory creation failed
          Shell parentShell = Display.getCurrent().getActiveShell();
          MessageDialog.openWarning(parentShell,  "Error",
            "The system failed to create a file folder for the Context"
            + " added before.");
        }
        else {
          
          newctx = newctx - 1;
          if (0 == newctx) {
            MessageDialog.openInformation(getShell(), "Context Created", "The"
                + " Contexts added is generated successfully.");
          }
        }
      }
    }
    
  }
  
  /**
   * Update Context directories in the task sources of the Mechanic preference page.
   *
   */
  private void updateCtxDir () {
    
    // if the user change the selected context
    if (selContext != preSelContext) {
      // TODO JL context has changed
      // record info about context switch
      
      // whether there exist selected Contexts, delete all previous ones first
      taskSrc.removeAllCtxDirFromTaskSrc();
      if (this.selContext != null) {
        // if (addDirectoryToPrefsFile(selContext.getFileLocation())) {
        if (taskSrc.addDirectoryToTaskSrc(selContext.getFileLocation())) {
        }
        else {
          Shell parentShell = Display.getCurrent().getActiveShell();
          MessageDialog.openWarning(parentShell,  "Same Directories",
              "There already exist a directory in the list. Please select"
              + " another one");
        }
      }
    }
  }
  
  /**
   * Restore all the preferences to default values. (The implementation of the 
   * method is left for the furture)
   *
   */
  private void ResDefPreferences() {
        
//    PreferenceManager prefmngr = PlatformUI.getWorkbench( ).getPreferenceManager();
//    List<IPreferenceNode> prefnodelist = prefmngr.getElements(PreferenceManager.PRE_ORDER);
//
//    for(IPreferenceNode prefnode : prefnodelist){
//      
//      if (null != prefnode) {
//        // the IPreferenceNode doesn't store the preference page information.
//        IPreferencePage prefpage = prefnode.getPage();
//        
//        try {
//       // Use Reflection to visit the 
//          Method method = prefpage.getClass().getDeclaredMethod("performDefaults", null);
//          method.setAccessible(true);
//          try {
//            method.invoke(prefpage, null);
//          } catch (IllegalAccessException e) {
//            e.printStackTrace();
//          } catch (IllegalArgumentException e) {
//            e.printStackTrace();
//          } catch (InvocationTargetException e) {
//            e.printStackTrace();
//          }
//        } catch (NoSuchMethodException e) {
//          e.printStackTrace();
//        } catch (SecurityException e) {
//          e.printStackTrace();
//        }
//      }
//    }
    
  }
  
  /***
   * When the user clicks "OK" button, update the directories in the
   * "Task source" in Mechanic the preference page. And then write the
   * user's settings of contexts to the contexts.con file.
   *
   */
  @Override
  protected void okPressed() {
    
    createCtxDir();
    updateCtxDir();
    if (true == resDefPrefs) {
      ResDefPreferences();
      
    }
    
    if (ctxFile != null) {
      try {
        ctxsCollector.serializeContextsInfo(ctxFile);
      } catch (IOException e) {
        MessageDialog.openError(getParentShell(), "Couldn't save the Contexts", e.getMessage());
      }
    }
    
    super.okPressed();
  }
  
  /**
   * When the "Cancel" button is clicked, clear all the new added Contexts (if exist any),
   * by restore the original contexts information when the context switching window is opened.
   *
   */
  @Override
  protected void cancelPressed() {

    //initContextListTblBinding();
    
    if (0 == contextsDir.size()) {
      
      ctxsCollector.resetContextList(); 
      ctxsCollector.copyAllContexts(preCtxsCollector.getContextList());
    }
    else {
      
      boolean dialogopen = MessageDialog.open(MessageDialog.INFORMATION,
          getShell(), "Unsaved Context", "Are you sure you don't want to"
              + " create the new added Context?", SWT.NONE);
      
      if (false == dialogopen) {
        return;
      }
      else {
        contextsDir.clear(); 
      }
    }
    
    super.cancelPressed();
  }
}
